//
//  HJRefreshControl.swift
//  HJWeiBo
//
//  Created by 夏航军 on 16/9/30.
//  Copyright © 2016年 夏航军. All rights reserved.
//

import UIKit

private let refreshHeight: CGFloat = 44

//枚举刷新的三种状态
enum RefreshStatue : Int {
    case Normal = 0 //默认状态
    case Pulling //准备刷新
    case Refreshing //正在刷新
}

class HJRefreshControl: UIControl {

    
    var refreshStatue : RefreshStatue = .Normal {
        didSet {
            switch refreshStatue {
            case .Normal:
                //更新UI界面
                //不隐藏
                arrowIcon.isHidden = false
                tipLable.text = "下拉刷新"
                indicator.stopAnimating()
                
                //刷新结束之后调整contentInset.top 如果上一次是refreshing 则等刷新结束之后恢复原样
                if oldValue == .Refreshing {
                    UIView.animate(withDuration: 1, animations: {
                        self.scrollView!.contentInset.top = self.scrollView!.contentInset.top - refreshHeight
                    })
                }

                //设置箭头的转动
                UIView.animate(withDuration: 0.5, animations: {
                    
                    //修改箭头的transform
                    self.arrowIcon.transform = CGAffineTransform.identity
                })
                
            case .Pulling:
                arrowIcon.isHidden = false
                tipLable.text = "释放更新"
                indicator.stopAnimating()
                
                
                UIView.animate(withDuration: 0.5, animations: { 
                    self.arrowIcon.transform = CGAffineTransform.init(rotationAngle: CGFloat(M_PI))
                })
            case .Refreshing:
                arrowIcon.isHidden = true
                tipLable.text = "加载中"
                indicator.startAnimating()
                
                //刷新时更改scrollView的contentInset
                scrollView!.contentInset.top = scrollView!.contentInset.top + refreshHeight
                
                //让HJRefreshControl能够主动发送.valueChanged,从而能够调到loadData方法
                self.sendActions(for: .valueChanged)

            }
        }
    }
    
    
    //定义一个刷新结束的方法
    func stopAnimation() {
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now(), execute: {self.refreshStatue = .Normal
        })
    }
    
   
    override init(frame: CGRect) {
        
        let rect = CGRect(x: 0, y: -refreshHeight , width:KScreenW, height: refreshHeight)
        super.init(frame: rect)
        self.backgroundColor = #colorLiteral(red: 0.721568644, green: 0.8862745166, blue: 0.5921568871, alpha: 1)
        setupSubviews()
        
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?)
    {
        
        //1.获取滚动视图的contentOffset
        let offsetY = scrollView?.contentOffset.y ?? 0
        
        //2.确定临界值
        
        let targetY: CGFloat = -(scrollView!.contentInset.top + refreshHeight)
        
        if scrollView!.isDragging {
            //如果处于拖拽状态,并且处于下拉刷新,同时偏移值超过临界值,则把他设置为释放更新
            if refreshStatue == .Normal && offsetY < targetY   {
                refreshStatue = .Pulling
            }else if refreshStatue == .Pulling && offsetY > targetY {
                refreshStatue = .Normal
            }
        }else {
             //如果是释放更新状态 并且用户已经松手 就应该是 正在刷新状态
            if refreshStatue == .Pulling {
                refreshStatue = .Refreshing
            }
        }
    }
    
    
    
    
    override func willMove(toSuperview newSuperview: UIView?) {
        super.willMove(toSuperview: newSuperview)
        
        if let fatherView = newSuperview as? UIScrollView {
            //如果父视图是滚动视图就监听偏移量
            self.scrollView = fatherView
            fatherView.addObserver(self, forKeyPath: "contentOffset", options: .new, context: nil)
        }
    }
    
    
    
    //创建子控件并添加约束
    func setupSubviews() {
         addSubview(tipLable)
       addSubview(indicator)
       
        addSubview(arrowIcon)
        
        tipLable.snp.makeConstraints { (make) in
            make.centerX.equalTo(self).offset(10)
            make.centerY.equalTo(self)
        }
        
        indicator.snp.makeConstraints { (make) in
            make.centerY.equalTo(self)
            make.right.equalTo(tipLable.snp.left).offset(-5)
        }
        
        arrowIcon.snp.makeConstraints { (make) in
            
            make.center.equalTo(indicator)
        }
    }
    
    
    private var scrollView : UIScrollView?
    
    //箭头
        private lazy var arrowIcon : UIImageView = UIImageView(image:#imageLiteral(resourceName: "tableview_pull_refresh"))
    
    //提示信息
    private lazy var tipLable : UILabel = {
        
        let lable = UILabel(title: "下拉刷新", textColor: UIColor.orange, fontSize: 14)
        return lable
        
    }()
    
    //小菊花
    private lazy var indicator = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.white)
    
}









